import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { CartItem } from '@/types'
import api from '@/api/auth'

export const useCartStore = defineStore('cart', () => {
  const items = ref<CartItem[]>([])
  const loading = ref(false)

  // 计算属性
  const totalItems = computed(() => items.value.reduce((sum, item) => sum + item.quantity, 0))
  const totalAmount = computed(() => {
    return items.value.reduce((sum, item) => {
      const price = item.product.price * (1 - item.product.discount / 100)
      return sum + price * item.quantity
    }, 0)
  })

  // 获取购物车列表
  const fetchCart = async () => {
    try {
      loading.value = true
      const response = await api.get('/cart')
      items.value = response.items
    } catch (error) {
      console.error('Failed to fetch cart:', error)
    } finally {
      loading.value = false
    }
  }

  // 添加商品到购物车
  const addToCart = async (productId: string, quantity: number) => {
    try {
      loading.value = true
      const response = await api.post('/cart', { productId, quantity })
      items.value = response.items
      return true
    } catch (error) {
      console.error('Failed to add to cart:', error)
      return false
    } finally {
      loading.value = false
    }
  }

  // 更新购物车商品数量
  const updateQuantity = async (productId: string, quantity: number) => {
    try {
      loading.value = true
      const response = await api.put(`/cart/${productId}`, { quantity })
      items.value = response.items
      return true
    } catch (error) {
      console.error('Failed to update quantity:', error)
      return false
    } finally {
      loading.value = false
    }
  }

  // 从购物车移除商品
  const removeFromCart = async (productId: string) => {
    try {
      loading.value = true
      const response = await api.delete(`/cart/${productId}`)
      items.value = response.items
      return true
    } catch (error) {
      console.error('Failed to remove from cart:', error)
      return false
    } finally {
      loading.value = false
    }
  }

  // 清空购物车
  const clearCart = async () => {
    try {
      loading.value = true
      await api.delete('/cart')
      items.value = []
      return true
    } catch (error) {
      console.error('Failed to clear cart:', error)
      return false
    } finally {
      loading.value = false
    }
  }

  return {
    items,
    loading,
    totalItems,
    totalAmount,
    fetchCart,
    addToCart,
    updateQuantity,
    removeFromCart,
    clearCart
  }
}) 